<?php

namespace app\admin\controller\channel;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\Shop;
use app\admin\model\Admin;
use app\common\model\OrderProof;
use app\common\model\Order;
use app\api\service\UserService;
use think\Loader;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Channel extends Backend
{

    /**
     * Play模型对象
     * @var \app\admin\model\Play
     */
    protected $model = null;
    protected $noNeedRight = ['getbusinesstime'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Play;
        $this->view->assign("isPayList", $this->model->getIsPayList());
        $status = ['0'=>'未处理','1'=>'已处理'];
        $this->view->assign("statusList", $status);
        // 分发渠道
        $channel = Db::name('channel')->where(['status'=>1])->select();
        $this->channelList = [];
        foreach ($channel as $key => $value) {
            $this->channelList[$value['name']] = $value['id'];
        }
         // Db::connect(config('database.db2'));
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = input('filter','');
            $decode = json_decode($filter,1);
            $where2 = '';
            if (isset($decode['channel']) && $decode['channel']) {
                $where2 .= ' and play.channel like "%'.$decode['channel'].'%"';
            }
            if (isset($decode['virtual_num']) && $decode['virtual_num']) {
                $where2 .= ' and play.channel like "%'.$decode['virtual_num'].'%"';
            }
            if (isset($decode['end_time_str']) && $decode['end_time_str']) {
                $arr = explode(' - ', $decode['end_time_str']);
                $where2 .= ' and play.start_date='.strtotime($arr[0]).' and play.end_date='.strtotime($arr[1]);
            }
            if (isset($decode['play_type']) && $decode['play_type']) {
                if ($decode['play_type']==1) {
                    $where2 .= ' and play.play_type =1';
                } elseif($decode['play_type']==2) {
                    $where2 .= ' and play.play_type in (3,'.$decode['play_type'].')';
                }
            }
            if (isset($decode['phone']) && $decode['phone']) {
                $where2 .= ' and shop.phone like "%'.$decode['phone'].'%"';
            }
            if (isset($decode['shop.shop_name']) && $decode['shop.shop_name']) {
                $shop_no = Db::name('shop')->where('shop_name like "%'.$decode['shop.shop_name'].'%"')->value('group_concat(shop_no)');
                if ($shop_no) {
                    $where2 .= ' and play.shop_no in ('.$shop_no.')';
                } else {
                    $where2 .= ' and 1=2';
                }
            }
            if (isset($decode['play_channel.status']) && $decode['play_channel.status']) {
                if ($decode['play_channel.status']=='未分发') {
                    $decode['play_channel.status'] = 0;
                } elseif ($decode['play_channel.status']=='已分发') {
                    $decode['play_channel.status'] = 1;
                } elseif ($decode['play_channel.status']=='无法分发已处理') {
                    $decode['play_channel.status'] = 2;
                } elseif ($decode['play_channel.status']=='无法分发') {
                    $decode['play_channel.status'] = 3;
                } elseif ($decode['play_channel.status']=='已结束') {
                    $decode['play_channel.status'] = 4;
                }
                $where2 .= ' and play_channel.status='.$decode['play_channel.status'];
            }
            if (isset($decode['play_channel.operate_status']) && $decode['play_channel.operate_status']==0) {
                $orderstr = 'play_channel.update_dt asc';
            } else {
                $orderstr = 'play_channel.update_dt desc';
            }
            // 渠道权限
            $admin = session('admin');
            $auth_group_access = Db::name('auth_group_access')->where('uid',$admin['id'])->order('group_id desc')->find();
            $auth_group = Db::name('auth_group')->where('id',$auth_group_access['group_id'])->find();
            if (isset($this->channelList[$auth_group['name']])) {
                $where2 .= ' and play_channel.channel_id='.$this->channelList[$auth_group['name']];
            }
            $list = Db::name('play_channel')->alias('play_channel')
                ->field('play_channel.update_dt as update_dts,play_channel.connector,play_channel.activity_status,play_channel.id as play_channel_id,play_channel.status as channel_status,play_channel.quota,play_channel.channel_id,play_channel.operate_status,play.*,shop.shop_name,shop.address,shop.phone,shop.id as shopid')
                ->join('chbc_play play','play.id=play_channel.play_id ','left')
                ->join('chbc_shop shop','play.shop_no=shop.shop_no','left')
                ->where($where)
                ->where('play_channel.channel_id>3 and play_channel.status>=0 and play_channel.is_son=0'.$where2)
                ->order($orderstr)
                ->paginate($limit);
            $list2 = $list->items();

            foreach ($list2 as &$row) {
                $row['stock_text'] = '';
                $row['service_amt'] = '';
                $service_amt = [];
                if ($row['channel']) {
                    $channel=json_decode($row['channel'],1);
                    $row['channel'] = '';
                    $shop_serviceamt = Db::name('shop_serviceamt')->where(['shop_no'=>$row['shop_no'],'status'=>1])->field('service_amt,channel_id')->select();
                    foreach ($shop_serviceamt as $k => $v) {
                        $service_amt[$v['channel_id']] = $v['service_amt'];
                    }
                    $channelconsume = json_decode($row['channelconsume'],1);
                    foreach ($channel as $key => $value) {
                        // 分发状态
                        $row['channel'].='分发渠道：'.$value['channel_name'].'，';
                        $row['channel'].='名额：'.$value['quota'].'，';
                        if ($value['channel_status']=='未分发') {
                            $row['channel'].='状态：<span style="color:red;">'.$value['channel_status'].'</span>；</br>';
                        } elseif ($value['channel_status']=='已分发') {
                            $row['channel'].='状态：<span style="color:green;">'.$value['channel_status'].'</span>；</br>';
                        } elseif ($value['channel_status']=='无法分发') {
                            $row['channel'].='状态：<span style="color:orange;">'.$value['channel_status'].'</span>；</br>';
                        } else {
                            $row['channel'].='状态：'.$value['channel_status'].'；</br>';
                        }
                        $firstRelease = Db::name('play')->field('id')->where('shop_no='.$row['shop_no'].' and channel like "%'.$value['channel_name'].'%"')->order('id ASC')->find();
                        if ($firstRelease['id']==$row['id']) {
                            $row['channel'] = trim($row['channel'],'</br>');
                            $row['channel'].='<span style="color:blue;">首发；</span></br>';
                        }
                        // 活动名额
                        if ($row['start_date']<1734192000) {
                            if ($value['channel_id']==3) {
                                $stock = intval(Db::name('play_order')->where(['play_no'=>$row['play_no'],'is_yunzhan'=>0,'order_status'=>['in',[3,6,-7,-8,-9]]])->count());
                                $stock = $value['quota']-$stock;
                            } else {
                                $stock = intval(Db::name('play_order')->where(['play_no'=>$row['play_no'],'is_yunzhan'=>$value['channel_id'],'order_status'=>['in',[3,6,-7,-8,-9]]])->count());
                                $stock = $value['quota']-$stock;
                            }
                        } else {
                            if ($value['channel_id']==3) {
                                $stock = $row['chbcconsume'];
                            } else {
                                $stock = isset($channelconsume[$value['channel_id']])?$channelconsume[$value['channel_id']]:0;
                                $stock = $value['quota']-$stock;
                            }
                        }
                        $row['stock_text'].='分发渠道：'.$value['channel_name'].'，';
                        $row['stock_text'].='库存：'.$stock.'/'.$value['quota'].'</br>';
                        // 服务费
                        $row['service_amt'].='分发渠道：'.$value['channel_name'].'，';
                        if (isset($service_amt[$value['channel_id']])):
                            $row['service_amt'].='服务费：'.$service_amt[$value['channel_id']].'</br>';
                        else:
                            $row['service_amt'].='</br>';
                        endif;
                    }   
                }
                if (isset($service_amt[$row['channel_id']])) {
                    $row['back_money_text'] = '满'.intval($row['user_pay']).'返'.round($row['shop_settlement']-$service_amt[$row['channel_id']],2);
                } else {
                    $row['back_money_text'] = $this->model->getBackMoneyText2Attr($row['shop_settlement'],$row);
                }
                $row['start_time_str'] = $row['start_time_str'].'~'.$row['end_time_str'];
                // 渠道活动状态
                //当我方活动状态是 进行中 并且分发状态是 未分发 ，则渠道活动状态为 活动发布
                if ($row['play_status']==2 && $row['channel_status']==0) {
                    $row['activity_status'] = '活动发布';
                } elseif ($row['play_status']==2 && $row['channel_status']==1 && $row['activity_status']==1) {//当我方活动状态是 进行中 并且分发状态是 已分发，活动名额有修改，则渠道活动状态为活动调整
                    $row['activity_status'] = '活动调整';
                } elseif (in_array($row['play_status'],[3,4,5]) && $row['activity_status']==2) {//当我方进行中的活动被业务员手动改为结束时，则渠道活动状态为活动结束
                    $row['activity_status'] = '活动结束';
                } else {
                    $row['activity_status'] = '活动发布';
                }
                if ($row['channel_status']==0) {
                    $row['channel_status'] = '未分发';
                } elseif ($row['channel_status']==1) {
                    $row['channel_status'] = '已分发';
                } elseif ($row['channel_status']==2) {
                    $row['channel_status'] = '无法分发已处理';
                } elseif ($row['channel_status']==3) {
                    $row['channel_status'] = '无法分发';
                } elseif ($row['channel_status']==4) {
                    $row['channel_status'] = '已结束';
                }
                $play_channel = ['status' => $row['channel_status'],'quota' => $row['quota'],'channel_id' => $row['channel_id'],'id' => $row['play_channel_id'],'operate_status' => $row['operate_status'],'update_dt' => $row['update_dts']];
                $play_channel['connector'] = Db::name('admin')->where('id',$row['connector'])->value('nickname');
                $row['play_channel'] = $play_channel;
                $shop = ['shop_name' => $row['shop_name'],'address' => $row['address'],'id' => $row['shopid']];
                $row['shop'] = $shop;
                // 待上传
                $row['total_pay'] = 0;
                // 待审核
                $row['total_service_amt'] = 0;
                // 已完成
                $row['acture_pay'] = Db::name('play_order')->where(['play_no'=>$row['play_no'],'order_status'=>3])->count();
                
                if ($row['pay_status']==0 && in_array($row['play_status'], [0,1,2,4])) {
                    $row['pay_status'] = '';
                }
                // 金额是商家实际要支付的，待支付状态才显示
                $row['total_money'] = '';
                if ($row['play_status']==3) {
                    $row['total_money'] = (float)Db::name('play_order')->where(['play_no'=>$row['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                }
                $row['user_id'] += config('virtual_userid');
                $row['end_time_str'] = date('Y-m-d',$row['start_date']).' 至 '.date('Y-m-d',$row['end_date']);
                // 分发状态
                $row['virtual_num'] = $row['channel'];
                $row['parent_play_no'] = $row['parent_play_no']==0?'否':'是';
                $qrcode_pic = Db::name('shop_platform')->where('shop_no',$row['shop_no'])->value('qrcode_pic');
                $row['create_by'] = strpos($qrcode_pic,'://')===false?config('upload_domain').$qrcode_pic:$qrcode_pic;
                $row['super_play_no'] = $row['super_play_no']==0?0:1;
            }

            $result = array("total" => $list->total(), "rows" => $list2);

            return json($result);
        }
        $salesmanList = [];
        // 渠道业务员
        $auth_group = Db::name('auth_group')->where('pid',15)->value('group_concat(id)');
        $auth_group_access = Db::name('auth_group_access')->where('group_id in ('.$auth_group.')')->value('group_concat(uid)');
        $admin = Db::name('admin')->where('id in ('.$auth_group_access.')')->field('id,nickname')->select();
        foreach ($admin as $ad) {
            $salesmanList[$ad['id']] = $ad['nickname'];
        }
        $this->assignconfig(['salesmanList' => $salesmanList,'channelList'=>$this->channelList]);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edits($ids = null)
    {
        $play_channel = Db::name('play_channel')->where('id='.$ids)->find();
        $row = $this->model->get($play_channel['play_id']);
        $row['start_date'] = date('Y-m-d',$row['start_date']);
        $row['end_date'] = date('Y-m-d',$row['end_date']);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // 渠道权限
        $admin = session('admin');
        $auth_group_access = Db::name('auth_group_access')->where('uid',$admin['id'])->order('group_id desc')->find();
        $auth_group = Db::name('auth_group')->where('id',$auth_group_access['group_id'])->find();
        if ((isset($this->channelList[$auth_group['name']]) && $this->channelList[$auth_group['name']]==$play_channel['channel_id']) || $auth_group['id']==1) {

        } else {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {
            $ids = input('ids',0);

        }
        //当我方活动状态是 进行中 并且分发状态是 未分发 ，则渠道活动状态为 活动发布
        if ($row['play_status']==2 && $play_channel['status']==0) {
            $play_channel['activity_status'] = '活动发布';
        } elseif ($row['play_status']==2 && $play_channel['status']==1 && $play_channel['activity_status']==1) {//当我方活动状态是 进行中 并且分发状态是 已分发，活动名额有修改，则渠道活动状态为活动调整
            $play_channel['activity_status'] = '活动调整';
        } elseif (in_array($row['play_status'],[3,4,5]) && $play_channel['activity_status']==2) {//当我方进行中的活动被业务员手动改为结束时，则渠道活动状态为活动结束
            $play_channel['activity_status'] = '活动结束';
        } else {
            $play_channel['activity_status'] = '活动发布';
        }
        if ($play_channel['status']==0) {
            $play_channel['status'] = '未分发';
        } elseif ($play_channel['status']==1) {
            $play_channel['status'] = '已分发';
        } elseif ($play_channel['status']==2) {
            $play_channel['status'] = '无法分发已处理';
        } elseif ($play_channel['status']==3) {
            $play_channel['status'] = '无法分发';
        } elseif ($play_channel['status']==4) {
            $play_channel['status'] = '已结束';
        }
        if ($play_channel['operate_status']==1) {
            $play_channel['operate_status'] = '已处理';
        } else {
            $play_channel['operate_status'] = '未处理';
        }
        $shop = Db::name('shop')->where('shop_no='.$row['shop_no'])->field('*')->find();
        $shopModel = new \app\admin\model\Shop();
        $shop['shop_type_text'] = $shopModel->getShopTypeTextAttr($shop['shop_type'],$shop);
        $qrcode_pic = Db::name('shop_platform')->where('shop_no',$row['shop_no'])->value('qrcode_pic');
        $row['create_by'] = strpos($qrcode_pic,'://')===false?config('upload_domain').$qrcode_pic:$qrcode_pic;
        // 餐标
        $service_amt = [];
        $shop_serviceamt = Db::name('shop_serviceamt')->where(['shop_no'=>$row['shop_no'],'status'=>1])->field('service_amt,channel_id')->select();
        foreach ($shop_serviceamt as $k => $v) {
            $service_amt[$v['channel_id']] = $v['service_amt'];
        }
        if (isset($service_amt[$play_channel['channel_id']])) {
            $back_money_text = '满'.intval($row['user_pay']).'返'.round($row['shop_settlement']-$service_amt[$play_channel['channel_id']],2);
        } else {
            $back_money_text = $row['back_money_text'];
        }
        // 渠道业务员
        $play_channel['connector'] = Db::name('admin')->where('id',$play_channel['connector'])->value('nickname');
        //是否首发
        $sf = Db::name('play_channel')->alias('pc')->field('pc.*')->join('chbc_play p','p.id=pc.play_id and pc.channel_id='.$play_channel['channel_id'])->where('p.shop_no='.$row['shop_no'])->order('p.id asc')->find();
        $firstRelease = 1;
        if ($sf['play_id']==$row['id']) {
            $firstRelease = 0;
        }
        $this->view->assign("back_money_text", $back_money_text);
        $this->view->assign("firstRelease", $firstRelease);
        $this->view->assign("row", $row);
        $this->view->assign("play_channel", $play_channel);
        $this->view->assign("shop", $shop);
        return $this->view->fetch();
    }
    
    /**
     * 已分发
     */
    public function agree($ids = null)
    {
        $play_channel = Db::name('play_channel')->where('id='.$ids)->find();
        $row = $this->model->lock(true)->where('id',$play_channel['play_id'])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($play_channel['status']!=0 || $play_channel['activity_status']!=0) {
            $this->error('状态有误，请重新进入页面再操作');
        }
        // 渠道权限
        $admin = session('admin');
        $auth_group_access = Db::name('auth_group_access')->where('uid',$admin['id'])->order('group_id desc')->find();
        $auth_group = Db::name('auth_group')->where('id',$auth_group_access['group_id'])->find();
        if ((isset($this->channelList[$auth_group['name']]) && $this->channelList[$auth_group['name']]==$play_channel['channel_id']) || $auth_group['id']==1) {

        } else {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isAjax()) {
            $result = false;
            Db::startTrans();
            try {
                // 改为已分发和已处理
                Db::name('play_channel')->where('id='.$ids)->update([
                    'status' => 1,
                    'operate_status' => 1,
                    'update_dt' => date('Y-m-d H:i:s')
                ]);
                $channel = json_decode($row['channel'],1);
                foreach ($channel as &$channels) {
                    if ($channels['channel_id']==$play_channel['channel_id']) {
                        $channels['channel_status'] = '已分发';
                    }
                }
                $json = json_encode($channel,JSON_UNESCAPED_UNICODE);
                $result = $row->allowField(true)->save([
                    'channel' => $json,
                ]);
                // 如果是循环活动，那他的子活动也要改
                if ($row['super_play_no']>0) {
                    Db::name('play')->where('parent_play_no',$row['super_play_no'])->update([
                        'channel' => $json,
                    ]);
                }
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
    }
    
    /**
     * 无法分发
     */
    public function refuse($ids = null)
    {
        $play_channel = Db::name('play_channel')->where('id='.$ids)->find();
        $row = $this->model->lock(true)->where('id',$play_channel['play_id'])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($play_channel['status']!=0 || $play_channel['activity_status']!=0) {
            $this->error('状态有误，请重新进入页面再操作');
        }
        // 渠道权限
        $admin = session('admin');
        $auth_group_access = Db::name('auth_group_access')->where('uid',$admin['id'])->order('group_id desc')->find();
        $auth_group = Db::name('auth_group')->where('id',$auth_group_access['group_id'])->find();
        if ((isset($this->channelList[$auth_group['name']]) && $this->channelList[$auth_group['name']]==$play_channel['channel_id']) || $auth_group['id']==1) {

        } else {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isAjax()) {
            $params = $this->request->param();
            if (!isset($params['remark'])) $this->error('缺少参数');
            $result = false;
            Db::startTrans();
            try {
                // 改为无法分发和已处理
                Db::name('play_channel')->where('id='.$ids)->update([
                    'status' => 3,
                    'operate_status' => 1,
                    'update_dt' => date('Y-m-d H:i:s'),
                    'remark' => htmlspecialchars(htmlentities($params['remark']))
                ]);
                $channel = json_decode($row['channel'],1);
                foreach ($channel as &$channels) {
                    if ($channels['channel_id']==$play_channel['channel_id']) {
                        $channels['channel_status'] = '无法分发';
                    }
                }
                $json = json_encode($channel,JSON_UNESCAPED_UNICODE);
                $result = $row->allowField(true)->save([
                    'channel' => $json,
                ]);
                // 如果是循环活动，那他的子活动也要改
                if ($row['super_play_no']>0) {
                    Db::name('play')->where('parent_play_no',$row['super_play_no'])->update([
                        'channel' => $json,
                    ]);
                }
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        $this->view->assign("play_channel", $play_channel);
        return $this->view->fetch();
    }
    
    /**
     * 已调整
     */
    public function adjust($ids = null)
    {
        $play_channel = Db::name('play_channel')->where('id='.$ids)->find();
        $row = $this->model->lock(true)->where('id',$play_channel['play_id'])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // 渠道权限
        $admin = session('admin');
        $auth_group_access = Db::name('auth_group_access')->where('uid',$admin['id'])->order('group_id desc')->find();
        $auth_group = Db::name('auth_group')->where('id',$auth_group_access['group_id'])->find();
        if ((isset($this->channelList[$auth_group['name']]) && $this->channelList[$auth_group['name']]==$play_channel['channel_id']) || $auth_group['id']==1) {

        } else {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isAjax()) {
            $result = false;
            Db::startTrans();
            try {
                // 改为无法分发和已处理
                Db::name('play_channel')->where('id='.$ids)->update([
                    // 'status' => 3,
                    'operate_status' => 1,
                    'update_dt' => date('Y-m-d H:i:s')
                ]);
                // $channel = json_decode($row['channel'],1);
                // foreach ($channel as &$channels) {
                //     if ($channels['channel_id']==$play_channel['channel_id']) {
                //         $channels['status'] = '无法分发';
                //     }
                // }
                // $result = $row->allowField(true)->save([
                //     'channel' => json_encode($channel,JSON_UNESCAPED_UNICODE),
                // ]);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $this->view->assign("row", $row);
        $this->view->assign("play_channel", $play_channel);
        return $this->view->fetch();
    }
    
    /**
     * 已结束
     */
    public function end($ids = null)
    {
        $play_channel = Db::name('play_channel')->where('id='.$ids)->find();
        $row = $this->model->lock(true)->where('id',$play_channel['play_id'])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // 渠道权限
        $admin = session('admin');
        $auth_group_access = Db::name('auth_group_access')->where('uid',$admin['id'])->order('group_id desc')->find();
        $auth_group = Db::name('auth_group')->where('id',$auth_group_access['group_id'])->find();
        if ((isset($this->channelList[$auth_group['name']]) && $this->channelList[$auth_group['name']]==$play_channel['channel_id']) || $auth_group['id']==1) {

        } else {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isAjax()) {
            $params = $this->request->param();
            if (!isset($params['remark'])) $this->error('缺少参数');
            $result = false;
            Db::startTrans();
            try {
                // 改为无法分发和已处理
                Db::name('play_channel')->where('id='.$ids)->update([
                    'status' => 4,
                    'operate_status' => 1,
                    'update_dt' => date('Y-m-d H:i:s'),
                    'remark' => htmlspecialchars(htmlentities($params['remark']))
                ]);
                $channel = json_decode($row['channel'],1);
                foreach ($channel as &$channels) {
                    if ($channels['channel_id']==$play_channel['channel_id']) {
                        $channels['channel_status'] = '已结束';
                    }
                }
                $json = json_encode($channel,JSON_UNESCAPED_UNICODE);
                $result = $row->allowField(true)->save([
                    'channel' => $json,
                ]);
                // 如果是循环活动，那他的子活动也要改
                if ($row['super_play_no']>0) {
                    Db::name('play')->where('parent_play_no',$row['super_play_no'])->update([
                        'channel' => $json,
                    ]);
                }
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        $this->view->assign("play_channel", $play_channel);
        return $this->view->fetch();
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        
        // 状态参数过滤掉
        if (isset($filter['end_time_str'])) {
            unset($filter['end_time_str']);
        }
        if (isset($filter['play_type'])) {
            unset($filter['play_type']);
        }
        if (isset($filter['channel'])) {
            unset($filter['channel']);
        }
        if (isset($filter['phone'])) {
            unset($filter['phone']);
        }
        if (isset($filter['virtual_num'])) {
            unset($filter['virtual_num']);
        }
        if (isset($filter['user_id'])) {
            $filter['user_id'] = $filter['user_id']-config('virtual_userid');
        }
        if (isset($filter['shop.shop_name'])) {
            unset($filter['shop.shop_name']);
        }
        if (isset($filter['play_channel.status'])) {
            unset($filter['play_channel.status']);
        }
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function($v){
                        return $v != '' && $v !== false && $v !== null;
                    })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }
}
